package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.domain.User;
import com.example.domain.vo.LoginUser;
import com.example.mapper.MenuMapper;
import com.example.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("用户名："+username);
        if (username.equals("")){
            throw new InternalAuthenticationServiceException("");
        }

    //1.连接数据库，根据查询用户查询账户信息
    QueryWrapper<User> queryWrapper=new QueryWrapper<>();
    queryWrapper.eq("user_name",username);
    User user = userMapper.selectOne(queryWrapper);
        if (user==null) {
            throw new UsernameNotFoundException("");
        }
    //如果没有查询到用户，就抛出异常
//    if(Objects.isNull(user)){
//        throw  new RuntimeException("用户名或密码错误");
//    }
    //TODO 查询用户对应的权限信息
    //2.赋权操作
        /**
         *  List<String> list =new ArrayList<>();
         *     list.add("select");
         *    list.add("delete");
          */
//       List<String> list = menuMapper.getMenuByUserId(user.getId());
//    //3.返回UserDetails对象
//    //如果有，把数据封装成UserDetails对象返回
//    return new LoginUser(user,list);
        List<String> list =  menuMapper.getPermsByUserId(user.getId());
        //如果有，把数据封装成UserDetails对象返回
        return new LoginUser(user,list);
    }
}
